import ChatSessionStateStore from "@/store/chat-session";
import {
  selectChatSessionList,
  insertChatSession,
  getSessionBySessionId,
  deleteChatSession,
  updateChatSession,
  clearSession,
  deleteBatchSessionsByIds,
} from "@/services/sqlite/chat-session";
import CurrentUserIdManager from "@/utils/user-utils";
import {
  ChatSession,
  ChatSessionCreate,
  ChatSessionUpdate,
} from "@/types/chat-session";
import {
  useChatSessionPageActions,
  useChatSessionPageState,
} from "@/hooks/chat/chat-session-page";

// 会话状态日志标识
const LOG_TAG = "📊 会话管理";

export const useChatSessionState = () => {
  const chatSessionState = ChatSessionStateStore((state) => state.state);
  const chatSessionPageState = useChatSessionPageState();

  return {
    ...chatSessionState,
    ...chatSessionPageState,
  };
};

export const useChatSessionActions = () => {
  const actions = ChatSessionStateStore((state) => state.actions);
  const chatSessionPageStateActions = useChatSessionPageActions();
  const ownerId = CurrentUserIdManager.getUserId();

  async function getSessions() {
    try {
      console.log(`${LOG_TAG}: 获取会话列表`);
      actions.setLoading(true);
      console.log(`${LOG_TAG}: 当前所有者ID: ${ownerId}`);
      const chatSessions: ChatSession[] = await selectChatSessionList(ownerId);
      console.log(`${LOG_TAG}: 成功获取 ${chatSessions.length} 个会话`);
      // 对会话进行排序
      const sortedSessions = [...chatSessions].sort((a, b) => {
        // 如果a被置顶而b没有，a排在前面
        if (a.pined && !b.pined) return -1;
        // 如果b被置顶而a没有，b排在前面
        if (!a.pined && b.pined) return 1;
        // 都是置顶或都不是置顶，按更新时间排序（新消息在前）
        return b.updateTime - a.updateTime;
      });
      actions.setSessions(sortedSessions);
    } catch (error) {
      console.error(`${LOG_TAG}: 获取会话列表失败:`, error);
    } finally {
      actions.setLoading(false);
    }
  }

  async function getSessionById(sessionId: string) {
    try {
      console.log(`${LOG_TAG}: 获取会话 ${sessionId}`);
      actions.setLoading(true);
      const session = await getSessionBySessionId({  sessionId , ownerId});
      if (session) {
        console.log(`${LOG_TAG}: 成功获取会话`, {
          sessionId: session.sessionId,
          sessionName: session.sessionName,
          sessionType: session.sessionType === 0 ? "单聊" : "群聊",
        });
        return session;
      } else {
        console.warn(`${LOG_TAG}: 会话 ${sessionId} 不存在`);
        return null;
      }
    } catch (error) {
      console.error(`${LOG_TAG}: 获取会话失败:`, error);
      return null;
    } finally {
      actions.setLoading(false);
    }
  }

  async function addSession(sessionCreate: Omit<ChatSessionCreate, "ownerId">) {
    try {
      console.log(`${LOG_TAG}: 创建新会话`, {
        sessionId: sessionCreate.sessionId,
        sessionType: sessionCreate.sessionType === 0 ? "单聊" : "群聊",
      });
      actions.setLoading(true);
      await insertChatSession({ ...sessionCreate, ownerId });
      const newSession = await getSessionBySessionId({
        ownerId,
        sessionId: sessionCreate.sessionId,
      });
      if (newSession) {
        console.log(`${LOG_TAG}: 会话创建成功`, {
          sessionId: newSession.sessionId,
          sessionName: newSession.sessionName,
          sessionType: newSession.sessionType === 0 ? "单聊" : "群聊",
        });
        actions.addSession(newSession);
      } else {
        console.error(`${LOG_TAG}: 会话创建但获取失败`);
      }
    } catch (error) {
      console.error(`${LOG_TAG}: 创建会话失败:`, error);
    } finally {
      actions.setLoading(false);
    }
  }

  async function deleteSession(sessionId: string) {
    try {
      console.log(`${LOG_TAG}: 删除会话 ${sessionId}`);
      actions.deleteSession(sessionId);
      await deleteChatSession({ ownerId, sessionId });
      console.log(`${LOG_TAG}: 会话 ${sessionId} 已删除`);
    } catch (error) {
      console.error(`${LOG_TAG}: 删除会话失败:`, error);
    }
  }

  async function deleteBatchSessions(sessionIds: string[]) {
    try {
      console.log(`${LOG_TAG}: 批量删除${sessionIds.length}个会话`);
      actions.setLoading(true);
      actions.deleteBatchSessions(sessionIds);
      await deleteBatchSessionsByIds(sessionIds, ownerId);
      console.log(`${LOG_TAG}: 批量删除会话完成`);
    } catch (error) {
      console.error(`${LOG_TAG}: 批量删除会话失败:`, error);
    } finally {
      actions.setLoading(false);
    }
  }

  async function updateSession(
    sessionUpdate: Omit<ChatSessionUpdate, "ownerId">
  ) {
    try {
      const updateInfo = Object.keys(sessionUpdate)
        .filter((key) => key !== "sessionId")
        .map((key) => `${key}=${sessionUpdate[key]}`)
        .join(", ");
      console.log(
        `${LOG_TAG}: 更新会话 ${sessionUpdate.sessionId} 信息: ${updateInfo}`
      );
      actions.updateSession(sessionUpdate);
      await updateChatSession({ ...sessionUpdate, ownerId });
    } catch (error) {
      console.error(`${LOG_TAG}: 更新会话失败:`, error);
    }
  }

  async function clearSessions() {
    try {
      console.log(`${LOG_TAG}: 清空所有会话`);
      actions.setLoading(true);
      actions.setSessions([]);
      await clearSession(ownerId);
      console.log(`${LOG_TAG}: 所有会话已清空`);
    } catch (error) {
      console.error(`${LOG_TAG}: 清空会话失败:`, error);
    } finally {
      actions.setLoading(false);
    }
  }

  return {
    getSessions,
    getSessionById,
    addSession,
    deleteSession,
    deleteBatchSessions,
    updateSession,
    clearSessions,
    ...chatSessionPageStateActions,
  };
};
